<?php

namespace common\models;

use Yii;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "ico_member".
 *
 * @property string $id
 * @property string $nickname
 * @property string $username
 * @property string $password
 * @property string $avatar
 * @property string $identity
 * @property string $realname
 * @property integer $status
 * @property integer $identity_type
 * @property string $mobile
 * @property string $email
 * @property string $pay_password
 * @property string $google_key
 * @property string $created_at
 * @property string $updated_at
 * @property string $count
 * @property string $from_uid
 * @property int $open_google_verify
 * @property string $token
 * @property LoginLog $lastLogin
 * @property LoginLog[] $loginLogs
 * @property int $last_login_id
 */
class IcoMember extends BaseActiveRecord implements IdentityInterface
{

    const IDENTITY_TYPE_NORMAL = 0;

    const STATUS_NORMAL = 0;


    const ONW_W_SEND_COUNT = 5000;

    const TWO_W_SEND_COUNT = 3000;

    const LEFT_W_SEND_COUNT = 1000;

    /**
     * 推广10个人
     */
    const BASE_SEND_COUNT = 10;

    const CACHE_KEY = 'icom:';

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'ico_member';
    }

    public function getAttributes($names = null, $except = [])
    {
        $data = parent::getAttributes($names = null, $except = []);
        $r['nickname'] = $data['nickname'];
        $r['id'] = intval($data['id']);
        $r['google_key'] = (string)$data['google_key'];
        $r['open_google_verify'] = (int)$data['open_google_verify'];
        $r['count'] = (double)$data['count'];
        $r['mobile'] = str_replace(mb_substr($data['mobile'],3,-3),'*****',$data['mobile']);
        $log = count($this->loginLogs)>1 ?
            $this->loginLogs[1]->getAttributes() :
            (count($this->loginLogs)==1 ?
                $this->loginLogs[0]->getAttributes():
                []
            );
        $r['lastLogin'] = $log;
        return $r;
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [[ 'mobile', 'password'], 'required'],
            [['id', 'status', 'identity_type','open_google_verify', 'last_login_id', 'created_at', 'updated_at', 'from_uid'], 'integer'],
            [['nickname', 'username', 'identity', 'realname'], 'string', 'max' => 20],
            [['password', 'email', 'pay_password'], 'string', 'max' => 100],
            [['avatar'], 'string', 'max' => 255],
            [['mobile'], 'string', 'max' => 11],
            [['mobile'], function($attr){
                $model = self::findOne(['mobile'=>$this->{$attr}]);
                if($model->id != $this->id){
                    $this->addError('mobile','手机号重复');
                }
            }],
            [['count'], 'safe'],
            [['google_key','token'], 'string', 'max' => 64],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => '自增id',
            'nickname' => '昵称',
            'username' => '用户名',
            'password' => '密码',
            'avatar' => '头像',
            'identity' => '身份证',
            'realname' => '真实姓名',
            'status' => '状态',
            'identity_type' => 'Identity Type',
            'mobile' => '手机号',
            'email' => '邮箱',
            'pay_password' => '支付密码',
            'google_key' => 'Google Key',
            'created_at' => '注册日期',
            'updated_at' => 'Updated At',
            'count' => 'AAA币数量',
            'token' => '登录token',
            'last_login_id' => '最后一次登录id',
        ];
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        $member = Yii::$app->cache->get(self::buildCacheKey($id));
        if(!empty($member)){
            return $member;
        }
        return static::findOne(['id' => $id]);
    }


    /**
     * @inheritdoc
     */
    public static function buildCacheKey($id)
    {
        return self::CACHE_KEY.$id;
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        $token = isset(\Yii::$app->request->headers['Token'])?\Yii::$app->request->headers['Token']:0;
        $uid = intval(\Yii::$app->cache->get($token));
        $member = static::findOne($uid);
        if(empty($member)){
            \Yii::$app->cache->delete($token);
            return null;
        }
        return $member;
    }

    /**
     * @inheritdoc
     */
    public static function logout()
    {
        $token = isset(\Yii::$app->request->headers['Token'])?\Yii::$app->request->headers['Token']:0;
        \Yii::$app->cache->delete($token);
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return 'aaa';
    }

    /**
     * @return LoginLog
     */
    public function getLastLogin()
    {
        return $this->hasOne(LoginLog::className(),['id'=>'last_login_id']);
    }

    /**
     * 最后两次登录
     * @return LoginLog[]
     */
    public function getLoginLogs()
    {
        return $this->hasMany(LoginLog::className(),['uid'=>'id'])->orderBy(['id'=>SORT_DESC])->limit(2);
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return true;
    }

    public function beforeSave($insert)
    {
        if($insert){
            $this->identity_type = self::IDENTITY_TYPE_NORMAL;
            //注册
            if(empty($this->nickname)){
                $this->nickname = $this->mobile;
            }
            if(empty($this->username)){
                $this->username = $this->mobile;
            }
            $this->password = md5($this->password);
            $this->checkRebate();
        }
        return parent::beforeSave($insert);
    }

    public function afterSave($insert,$changedAttributes)
    {
        if($insert){
            //注册
            if($this->count>0){
                $log = new IcoMoneyLog();
                $log->uid = $this->id;
                $log->before = 0;
                $log->after = $this->count;
                $log->count = $this->count;
                $log->desc = '注册赠送';
                $log->save();
            }
        }
        return parent::beforeSave($insert);
    }


    public function checkRebate()
    {
        $config = IcoConfig::findOne(['unit'=>'AAA']);
        if($config->left_count<($config->allcount/2)){
            //预留赠送
            return false;
        }

        //看当前用户有多少
        $allMemberCount = self::find()->sum('id');
        if($allMemberCount<10000){
            //小于1w
            $profit = self::ONW_W_SEND_COUNT;
        }
        elseif($allMemberCount<20000){
            //小于2w
            $profit = self::TWO_W_SEND_COUNT;
        }
        else{
            //2w以后
            $profit = self::LEFT_W_SEND_COUNT;
        }
        $this->count = $profit;
        $this->returnRebate($config,$profit);
        $config->reduce($profit);
    }

    /**
     * 返点
     * @param IcoConfig $config
     * @param $count
     * @return bool
     */
    public function returnRebate(IcoConfig $config,$count)
    {
        $fromUser = self::findOne($this->from_uid);
        if(empty($fromUser)){
            $this->from_uid = 0;
            return false;
        }
        $log = new IcoMoneyLog();
        $log->uid = $fromUser->id;
        $log->before = $fromUser->count;
        $fromUser->count += $count;
        $fromUser->save();
        $config->reduce($count);
        $log->count = $count;
        $log->after = $fromUser->count;
        $log->desc = sprintf('推荐用户:%s注册返利',$this->nickname);
        $log->save();
    }

}
